package kotan.service;

import kotan.AppEngineEnv;
import kotan.Kotan;

import org.apache.http.HttpHost;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;

public class HttpClientManager {

    protected final DefaultHttpClient httpClient;

    public HttpClientManager() {
        SchemeRegistry supportedSchemes = new SchemeRegistry();
        supportedSchemes.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
        // prepare parameters
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUseExpectContinue(params, true);
        HttpClientParams.setRedirecting(params, false); // disable auto redirect
        ClientConnectionManager connMgr = new ThreadSafeClientConnManager(params, supportedSchemes);
        httpClient = new DefaultHttpClient(connMgr, params);
    }

    public HttpClient getHttpClient() {
        return httpClient;
    }

    public HttpHost getHttpHost() {
        AppEngineEnv env = Kotan.get().getEnv();
        return new HttpHost(env.getHost(), env.getPort(), "http");
    }

    public HttpHost getHttpsHost() {
        AppEngineEnv env = Kotan.get().getEnv();
        return new HttpHost(env.getHost(), 443, "https");
    }

    public void shutdown() {
        httpClient.getConnectionManager().shutdown();
    }
}
